﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.SessionState;
using System.Data.OleDb;
using System.Configuration;
using System.Globalization;




namespace WeakEndForum
{
    public static class Constantes
    {
        public const string DB_NAME = "ForumUsersDatabase";
        public const string cultureParameter = "fr-CA";
        public const int ARTICLE_CONTENT_MAX_LENGTH = 300;
        public const int ARTICLE_TITLE_MAX_LENGTH = 30;
    }
    public static class Modules
    {
        public static bool isUserConnected()
        {
            bool userConnected = false;
            if (HttpContext.Current.Session["Username"] != null)
            {
                userConnected = true;
            }
            return userConnected;
        }
        public static string getConnectedUser()
        {
            return (string)HttpContext.Current.Session["Username"];
        }
        public static bool isDataReaderEmpty(OleDbDataReader _dataReader)
        {
            bool dataReaderEmpty = true;
            if (_dataReader.HasRows)
            {
                dataReaderEmpty = false;
            }
            return dataReaderEmpty;
        }
        public static bool verifyParameterExists(string _parameter, string _queryString)
        {
            bool parameterExists = false;
            if (_queryString != null)
            {
                parameterExists = true;
            }
            return parameterExists;
        }
        public static bool verifyUrlParameterIsInt(string _parameter, string _queryString)
        {
            if (verifyParameterExists(_parameter, _queryString))
            {
                try
                {
                    Convert.ToInt32(_queryString);
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        public static bool verifyRecordExistsInDB(string _field, string _table, string _queryString)
        {
            bool recordExists = false;
            OleDbConnection conn = new OleDbConnection(
            ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
            conn.Open();
            OleDbCommand command = new OleDbCommand("SELECT FIRST (" + _field + ") FROM " + _table + " WHERE ID=@queryString;", conn);
            command.Parameters.Add(new OleDbParameter("queryString", Convert.ToInt32(_queryString)) { OleDbType = OleDbType.Integer });
            command.Prepare();
            OleDbDataReader dataReader = command.ExecuteReader();
            if (dataReader.Read())
            {
                if (dataReader[0] != DBNull.Value)
                {
                    recordExists = true;
                }
            }
            conn.Close();
            return recordExists;
        }

        public static bool isRequestedQueryStringValid(string _parameter, string _field, string _table, out string _queryString)
        {
            bool queryPossible = false;
            string queryString = HttpContext.Current.Request.QueryString[_parameter];
            _queryString = queryString;
            if (verifyUrlParameterIsInt(_parameter, queryString))
            {
                queryPossible = verifyRecordExistsInDB(_field, _table, queryString);
            }
            return queryPossible;
        }

        public static bool isAdmin(string _username)
        {
            bool heIs = false;
            if (isUserConnected())
            {


                OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                conn.Open();
                OleDbCommand command = new OleDbCommand("SELECT Admin FROM Utilisateurs WHERE Username = @username", conn);
                command.Parameters.Add(new OleDbParameter("username", _username) { OleDbType = OleDbType.VarChar, Size = 255 });
                command.Prepare();
                OleDbDataReader dataReader = command.ExecuteReader();

                if (dataReader.Read())
                {
                    if ((bool)dataReader[0])
                    {
                        heIs = true;
                    }
                }
                conn.Close();
            }
            return heIs;
        }

        public static bool isMod(string _username)
        {
            bool heIs = false;
            if (isUserConnected())
            {

                OleDbConnection conn = new OleDbConnection(
                ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                conn.Open();
                OleDbCommand command = new OleDbCommand("SELECT Moderateur FROM Utilisateurs WHERE Username = @username", conn);
                command.Parameters.Add(new OleDbParameter("username", _username) { OleDbType = OleDbType.VarChar, Size = 255 });
                command.Prepare();
                OleDbDataReader dataReader = command.ExecuteReader();

                if (dataReader.Read())
                {
                    if ((bool)dataReader[0])
                    {
                        heIs = true;
                    }
                }
                conn.Close();
            }
            return heIs;
        }

        public static bool isBan(string _username)
        {
            bool heIs = false;
            OleDbConnection conn = new OleDbConnection(
            ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
            conn.Open();
            OleDbCommand command = new OleDbCommand("SELECT Ban FROM Utilisateurs WHERE Username = @username", conn);
            command.Parameters.Add(new OleDbParameter("username", _username) { OleDbType = OleDbType.VarChar, Size = 255 });
            command.Prepare();
            OleDbDataReader dataReader = command.ExecuteReader();

            if (dataReader.Read())
            {
                if ((bool)dataReader[0])
                {
                    heIs = true;
                }
            }
            conn.Close();
            return heIs;
        }
        public static HtmlGenericControl createDiv(string _cssClass)
        {
            HtmlGenericControl div = new HtmlGenericControl("div");
            div.Attributes.Add("class", _cssClass);
            return div;
        }
        public static void generateNews(OleDbDataReader _dataReader, ref PlaceHolder _ph)
        {
            if (!isDataReaderEmpty(_dataReader))
            {
                int nbSections = 3;
                for (int i = 0; _dataReader.Read(); i++)
                {
                    HtmlGenericControl article = createDiv("col-xs-12 col-md-6");
                    HtmlGenericControl wrapper = createDiv("newsFeedWrap");
                    //newsFeedPH.Controls.Add(div);
                    HtmlGenericControl[] divs = new HtmlGenericControl[nbSections];
                    divs[0] = createDiv("newsArticleTitle h2 RalewayFont");
                    divs[1] = createDiv("newsArticleDateSection small");
                    divs[2] = createDiv("newsArticleContent");
                    //Title section
                    HyperLink titleLink = new HyperLink();
                    titleLink.Text = trimString((string)_dataReader[1], Constantes.ARTICLE_TITLE_MAX_LENGTH);
                    titleLink.NavigateUrl = "Article.aspx?aID=" + ((int)_dataReader[0]).ToString();
                    divs[0].Controls.Add(titleLink);
                    //Date section
                    DateTime datePublication = (DateTime)_dataReader[3];
                    divs[1].InnerHtml = "Publié par <span class=\"text-primary\"><strong>" + (string)_dataReader[4] + "</strong></span> le " + DateManipulation.DateToString(datePublication) + ", à " + DateManipulation.TimeToString(datePublication) + ".";
                    if (isUserConnected())
                    {
                        if (isMod(getConnectedUser()) && getConnectedUser() == (string)_dataReader[4])
                        {
                            divs[1].InnerHtml += " | <a href=\"EditNews.aspx?aID=" + ((int)_dataReader[0]).ToString() + "\">Modifier</a>";
                        }
                    }
                    //Content section
                    divs[2].InnerText = trimString((string)_dataReader[2], Constantes.ARTICLE_CONTENT_MAX_LENGTH);

                    for (int j = 0; j < nbSections; j++)
                    {
                        wrapper.Controls.Add(divs[j]);
                    }
                    article.Controls.Add(wrapper);
                    _ph.Controls.Add(article);
                }

            }
            else
            {
                HtmlGenericControl wrapper = createDiv("newsFeedWrap");
                wrapper.InnerText = "Il n'y a actuellement aucune nouvelle.";
                _ph.Controls.Add(wrapper);
            }
        }
        public static void generateNewsDetailed(OleDbDataReader _dataReader, ref PlaceHolder _ph)
        {
            if (!isDataReaderEmpty(_dataReader))
            {
                int nbSections = 3;
                for (int i = 0; _dataReader.Read(); i++)
                {
                    HtmlGenericControl article = createDiv("col-xs-12 col-md-12");
                    HtmlGenericControl wrapper = createDiv("newsFeedWrap enableCarriageReturn");
                    HtmlGenericControl[] divs = new HtmlGenericControl[nbSections];
                    divs[0] = createDiv("newsArticleTitle h2 RalewayFont");
                    divs[1] = createDiv("newsArticleDateSection small");
                    divs[2] = createDiv("newsArticleContent");
                    //Title section
                    divs[0].InnerText = (string)_dataReader[1];
                    //Date section
                    DateTime datePublication = (DateTime)_dataReader[3];
                    divs[1].InnerHtml = "Publié par <span class=\"text-primary\"><strong>" + (string)_dataReader[4] + "</strong></span> le " + DateManipulation.DateToString(datePublication) + ", à " + DateManipulation.TimeToString(datePublication) + ".";
                    if (isUserConnected())
                    {
                        if (isMod(getConnectedUser()) && getConnectedUser() == (string)_dataReader[4])
                        {
                            divs[1].InnerHtml += " | <a href=\"EditNews.aspx?aID=" + ((int)_dataReader[0]).ToString() + "\">Modifier</a>";
                        }
                    }
                    //Content section
                    divs[2].InnerText = (string)_dataReader[2];

                    for (int j = 0; j < nbSections; j++)
                    {
                        wrapper.Controls.Add(divs[j]);
                    }
                    article.Controls.Add(wrapper);
                    _ph.Controls.Add(article);
                }

            }
            else
            {
                HtmlGenericControl article = createDiv("col-xs-12 col-md-12");
                HtmlGenericControl wrapper = createDiv("newsFeedWrap");
                wrapper.InnerText = "Il n'y a actuellement aucune nouvelle.";
                article.Controls.Add(wrapper);
                _ph.Controls.Add(article);
            }
        }
        public static string trimString(string _content, int _length)
        {
            if (_content.Length >= _length)
            {
                int i = _length;
                while (_content.Substring(i, 1) != " ")
                {
                    i++;
                }
                    return _content.Substring(0, i) + "...";
            }
            return _content;
        }
    }
    public static class DateManipulation
    {
        public static string DateToString(DateTime _date)
        {
            CultureInfo culture = new CultureInfo(Constantes.cultureParameter);
            return _date.ToString("D", culture);
        }
        public static string TimeToString(DateTime _date)
        {
            CultureInfo culture = new CultureInfo(Constantes.cultureParameter);
            return _date.ToString("t", culture);
        }
    }
}